<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <el-upload
        class="upload-demo"
        :on-preview="handlePreview"
        :action="$uploadImg"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :file-list="fileList"
        :multiple="true"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>
  </div>
</template>

<script>
import {qualification,save} from "@/api/admin/schoolFood"

export default {

  data() {
    return {
      fileList: [],
      file:[]
    }
  },
  mounted() {
    this.InitFn()
  },

 methods: {
  // 初始化
  async InitFn() {
    qualification().then(res => {
      console.log('接口返回的数据:', res);
      if (res.code === 0) {
        const fileUrls = res.data.split(','); // 将字符串按逗号分割成数组
        this.fileList = fileUrls.map(url => ({
          name: url.split('/').pop(), // 使用文件路径的最后一部分作为文件名
          url: url
        }));
        this.file = fileUrls; // 直接将文件路径数组赋值给 file
      } else {
        this.$message({
          type: 'error',
          message: res.msg
        });
      }
    }).catch(error => {
      console.error('请求失败:', error);
      this.$message({
        type: 'error',
        message: '请求失败，请稍后再试'
      });
    });
  },
  handleSuccess(file) {
    if (file.code == 0) {
      this.fileList.push({ name: file.data.name, url: file.data.name });
      this.file.push(file.data.name);
      save(this.file).then(res => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
      });
    } else {
      this.$message({
        type: 'error',
        message: file.msg
      });
    }
    console.log('file:', file.data.name);
  },
   handleRemove(file, fileList) {
     // 从 fileList 中移除指定的文件对象
     const fileIndex = this.fileList.findIndex(f => f.url === file.url);
     if (fileIndex !== -1) {
       this.fileList.splice(fileIndex, 1);
     }

     // 从 file 数组中移除指定的文件路径
     const filePathIndex = this.file.indexOf(file.url);
     if (filePathIndex !== -1) {
       this.file.splice(filePathIndex, 1);
     }

     // 调用 save 方法保存更新后的 file 数组
     save(this.file).then(res => {
       this.$message({
         type: 'success',
         message: '保存成功'
       });
     }).catch(error => {
       console.error('保存失败:', error);
       this.$message({
         type: 'error',
         message: '保存失败，请稍后再试'
       });
     });
   },
   handlePreview(file) {
     console.log(file);
   }
}

}
</script>
<style>
.lead-list {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fddeae;
  margin-bottom: 5px;
  border-radius: 2px;
  padding: 5px 0;
}

.lead-list:last-child {
  margin-bottom: 0;
}

.lead-list span {
  margin-right: 30px;
}
.tableline i{
  font-style: normal;
}
</style>

